import ctypes
from ctypes import wintypes
import time

user32   = ctypes.windll.user32
kernel32 = ctypes.windll.kernel32
psapi    = ctypes.windll.psapi

class RECT(ctypes.Structure):
    _fields_ = [("left", wintypes.LONG),
                ("top",  wintypes.LONG),
                ("right", wintypes.LONG),
                ("bottom", wintypes.LONG)]

PROCESS_QUERY_INFORMATION = 0x0400
PROCESS_VM_READ           = 0x0010

def get_focus_window_info():
    hwnd = user32.GetForegroundWindow()
    if not hwnd:
        return None

    length = user32.GetWindowTextLengthW(hwnd) + 1
    buff_title = ctypes.create_unicode_buffer(length)
    user32.GetWindowTextW(hwnd, buff_title, length)

    buff_class = ctypes.create_unicode_buffer(256)
    user32.GetClassNameW(hwnd, buff_class, 256)

    rect = RECT()
    user32.GetWindowRect(hwnd, ctypes.byref(rect))

    pid = wintypes.DWORD()
    user32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid))

    h_proc = kernel32.OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
                                  False, pid.value)
    exe_path = ""
    if h_proc:
        exe_name = ctypes.create_unicode_buffer(260)
        if psapi.GetModuleFileNameExW(h_proc, None, exe_name, 260):
            exe_path = exe_name.value
        kernel32.CloseHandle(h_proc)

    return {
        "hwnd": hwnd,
        "title": buff_title.value,
        "class_name": buff_class.value,
        "rect": (rect.left, rect.top, rect.right, rect.bottom),
        "pid": pid.value,
        "exe": exe_path
    }

if __name__ == "__main__":
    try:
        while True:
            info = get_focus_window_info()
            print("=" * 60)
            for k, v in info.items():
                print(f"{k:10}: {v}")
            time.sleep(10)          # 每 10 秒刷新一次
    except KeyboardInterrupt:
        print("\n已停止监控。")